package com.taptech.doufu.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.view.View;

import com.taptech.doufu.R;
import com.taptech.doufu.ui.view.DiaobaoTextView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by longsiyang on 15/11/16.
 */
public class TextLinkClickHelper {

    static Context mContext;

    static List<int[]> deleteList;



    /**
     * 使textview中的字符中的链接变色
     * @param context
     * @param textView
     * @param content
     * @param specialList
     * @return
     */
    static public SpannableStringBuilder getSpanString(Context context , DiaobaoTextView textView , CharSequence content , List<int[]> specialList) {

        mContext = context;
        deleteList = new ArrayList<>();
        if (content != null && !TextUtil.isEmpty(content.toString())) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            SpannableStringBuilder ssb = getClickString(content , specialList);
            return ssb;

        }
        return null;
    }

    static private SpannableStringBuilder getClickString(CharSequence content , List<int[]> specialList) {

        SpannableStringBuilder spannableString = new SpannableStringBuilder(content);
        Pattern p = Pattern.compile("\\[[^@\\[\\]]{2,}\\]\\([^\\(\\)]{2,}\\)");
        Matcher m = p.matcher(spannableString);
        while (m.find()) {


            int start = m.start();
            int end = m.end();

            // 获取标题的start和end
            Pattern pTitle = Pattern.compile("\\[[^@\\[\\]]{2,}\\]");
            Matcher mTitle = pTitle.matcher(spannableString);
            int titleStart = start ;
            int titleEnd = start ;
            CharSequence title = null;


            while (mTitle.find()) {
                titleStart = mTitle.start();
                titleEnd = mTitle.end();
                if (titleStart == start) {
                    title = spannableString.subSequence(titleStart + 1, titleEnd - 1);
                    break;
                }
            }
            // 获取链接的start和end
            Pattern pLink = Pattern.compile("\\([^\\(\\)]{2,}\\)");
            Matcher mLink = pLink.matcher(spannableString);

            int linkStart = end;
            int linkEnd = end;
            CharSequence url = null;
            while (mLink.find()) {
                linkStart = mLink.start();
                linkEnd = mLink.end();
                if (linkEnd == end) {
                    url = spannableString.subSequence(linkStart + 1, linkEnd - 1);

                    break;
                }
            }
            TTLog.d("tag", "the des ====url is " + url);
            spannableString.setSpan(new Clickable(title, url), start + 1, titleEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.note_content_link_icon);
            drawable.setBounds(0 , 0 , ScreenUtil.dip2px(mContext , 23) , ScreenUtil.dip2px(mContext , 12) );
            spannableString.setSpan(new iconSpanable(drawable), start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            deleteList.add(new int[]{linkStart, linkEnd});
            specialList.add(new int[]{titleStart  , titleEnd - 1});



        }
        // 因为是删除，所以必须用倒序
        for (int i = deleteList.size() -1 ; i >= 0 ; i --){
            int [] deletePos = deleteList.get(i);
            spannableString.delete(deletePos[0] - 1, deletePos[1]);
            if (i < deleteList.size() -1){
                int length = deletePos[1] - deletePos[0] + 1;
                int specialStart = specialList.get(i)[0];
                int specialEnd = specialList.get(i + 1)[1];
                specialStart -= length;
                specialEnd -= length;
                specialList.set(i , new int[]{specialStart , specialEnd});
            }

        }

        return spannableString;
    }



    static private class iconSpanable extends ImageSpan{

        public iconSpanable(Drawable drawable){
            //super(drawable, ImageSpan.ALIGN_BASELINE);
            super(drawable);

        }

        public int getSize(Paint paint, CharSequence text, int start, int end,
                           Paint.FontMetricsInt fontMetricsInt) {
            Drawable drawable = getDrawable();
            Rect rect = drawable.getBounds();
            if (fontMetricsInt != null) {
                Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
                int fontHeight = fmPaint.bottom - fmPaint.top;
                int drHeight = rect.bottom - rect.top;

                int top = drHeight / 2 - fontHeight / 4;
                int bottom = drHeight / 2 + fontHeight / 4;

                fontMetricsInt.ascent = -bottom;
                fontMetricsInt.top = -bottom;
                fontMetricsInt.bottom = top;
                fontMetricsInt.descent = top;
            }
            return rect.right;
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end,
                         float x, int top, int y, int bottom, Paint paint) {
            Drawable drawable = getDrawable();
            canvas.save();
            int transY = 0;
            transY = ((bottom + top) - drawable.getBounds().bottom) / 2 ;
            canvas.translate(x, transY);
            drawable.draw(canvas);
            canvas.restore();
        }

    }


    static private class Clickable extends ClickableSpan implements View.OnClickListener {

        CharSequence linkTitle;
        CharSequence linkUrl;

        public Clickable(CharSequence content, CharSequence url) {
            linkTitle = content;
            linkUrl = url;
        }



        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(Color.parseColor("#549ee0"));
            // 去掉下划线
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View view) {
            if (linkTitle != null && !TextUtil.isEmpty(linkTitle.toString()) && linkUrl != null && !TextUtil.isEmpty(linkUrl.toString())) {
                Uri uri = Uri.parse(linkUrl.toString());
                Intent intent = new Intent(Intent.ACTION_VIEW , uri);
                intent.setClassName("com.android.browser",
                        "com.android.browser.BrowserActivity");
                mContext.startActivity(intent);

            }

        }
    }


}

